#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

typedef struct Usr
{
	int iId;
	char caName[32];
	int iAge;
	float fMoney;

	struct Usr *next;
}Usr;

typedef struct List
{
	int iLen;
	Usr *pFirstNode;
}List;

Usr *mkUsrNode()
{
	Usr *node = (Usr*)malloc(sizeof(Usr));
	if (NULL == node)
	{
		exit(EXIT_FAILURE);
	}
	memset(node, 0, sizeof(Usr));
	return node;
}

List *mkList()
{
	List *list = (List*)malloc(sizeof(List));
	if (NULL == list)
	{
		exit(EXIT_FAILURE);
	}
	memset(list, 0, sizeof(List));
	return list;
}

void insert(List *list, Usr *node)
{
	if (NULL == list || NULL == node)
	{
		return;
	}
	node->next = list->pFirstNode;
	list->pFirstNode = node;	
	list->iLen++;
}

void display(const List *list)
{
	if (NULL == list)
	{
		return;
	}

	Usr *node = list->pFirstNode;
	while (NULL != node)
	{
		printf("id=%d,name=%s,age=%d,money=%.1f\n"
			   , node->iId, node->caName, node->iAge
			   , node->fMoney);
		node = node->next;
	}
}

void input(Usr *node)
{
	if (NULL == node)
	{
		return;
	}
	printf("请输入人员信息id,name,age,money:\n");
	scanf("%d%s%d%f", &node->iId, node->caName
					, &node->iAge, &node->fMoney);
}

int comByAge(const void *d1, const void *d2)
{
	return (*(Usr**)d1)->iAge > (*(Usr**)d2)->iAge;
}

void sortByAge(List *list)
{
	if (NULL == list)
	{
		return;
	}
	//产生一个存放节点地址的数组
	Usr **arr = (Usr**)malloc(sizeof(Usr*)*(list->iLen));
	Usr *node = list->pFirstNode;
	int i = 0;
	//将所有节点的地址存放到数组中
	for (; i<list->iLen; i++)
	{
		arr[i] = node;
		node = node->next;
	}	
	qsort(arr, list->iLen, sizeof(Usr*), comByAge);
	for (i=0; i<list->iLen; i++)
	{
		printf("id=%d,name=%s,age=%d,money=%.1f\n"
			   , arr[i]->iId, arr[i]->caName, arr[i]->iAge
			   , arr[i]->fMoney);
	}
	free(arr);
}

int main(int argc, char *argv[])
{	
	List *list = mkList();
	Usr *node = NULL;
	int i = 0;
	for (; i<5; i++)
	{
		node = mkUsrNode();
		input(node);
		insert(list, node);
	}
	display(list);
	sortByAge(list);

	return 0;
}
